import AsyncStorage from '@react-native-async-storage/async-storage';
import { Platform } from 'react-native';
import axios from 'axios';
import { API_BASE_URL } from '../api/config';

type StorageKey = string;
type StorageValue = string | null;
type StorageKeyValuePair = [StorageKey, StorageValue];

interface IStorage {
  getItem(key: StorageKey): Promise<StorageValue>;
  setItem(key: StorageKey, value: string): Promise<void>;
  removeItem(key: StorageKey): Promise<void>;
  multiGet(keys: StorageKey[]): Promise<StorageKeyValuePair[]>;
  multiRemove(keys: StorageKey[]): Promise<void>;
}

// 创建一个空的存储实现用于服务器端
const createEmptyStorage = (): IStorage => ({
  async getItem() { return null; },
  async setItem() {},
  async removeItem() {},
  async multiGet(keys: StorageKey[]) { return keys.map(key => [key, null]); },
  async multiRemove() {},
});

// Web 存储适配器
class WebStorageAdapter implements IStorage {
  constructor(private localStorage: globalThis.Storage) {}

  async getItem(key: StorageKey): Promise<StorageValue> {
    return this.localStorage.getItem(key);
  }

  async setItem(key: StorageKey, value: string): Promise<void> {
    this.localStorage.setItem(key, value);
  }

  async removeItem(key: StorageKey): Promise<void> {
    this.localStorage.removeItem(key);
  }

  async multiGet(keys: StorageKey[]): Promise<StorageKeyValuePair[]> {
    const results: StorageKeyValuePair[] = [];
    for (const key of keys) {
      results.push([key, this.localStorage.getItem(key)]);
    }
    return results;
  }

  async multiRemove(keys: StorageKey[]): Promise<void> {
    keys.forEach(key => this.localStorage.removeItem(key));
  }
}

// AsyncStorage 适配器
class AsyncStorageAdapter implements IStorage {
  async getItem(key: StorageKey): Promise<StorageValue> {
    return await AsyncStorage.getItem(key);
  }

  async setItem(key: StorageKey, value: string): Promise<void> {
    await AsyncStorage.setItem(key, value);
  }

  async removeItem(key: StorageKey): Promise<void> {
    await AsyncStorage.removeItem(key);
  }

  async multiGet(keys: StorageKey[]): Promise<StorageKeyValuePair[]> {
    const result = await AsyncStorage.multiGet(keys);
    return result as StorageKeyValuePair[];
  }

  async multiRemove(keys: StorageKey[]): Promise<void> {
    await AsyncStorage.multiRemove(keys);
  }
}

class Storage implements IStorage {
  private static instance: Storage;
  private storage: IStorage;

  private constructor() {
    // 检查是否在服务器端环境
    if (typeof window === 'undefined') {
      this.storage = createEmptyStorage();
    } else if (Platform.OS === 'web') {
      this.storage = new WebStorageAdapter(window.localStorage);
    } else {
      this.storage = new AsyncStorageAdapter();
    }
  }

  public static getInstance(): Storage {
    if (!Storage.instance) {
      Storage.instance = new Storage();
    }
    return Storage.instance;
  }

  async getItem(key: StorageKey): Promise<StorageValue> {
    try {
      return await this.storage.getItem(key);
    } catch (error) {
      console.error('Error getting item from storage:', error);
      return null;
    }
  }

  async setItem(key: StorageKey, value: string): Promise<void> {
    try {
      await this.storage.setItem(key, value);
    } catch (error) {
      console.error('Error setting item in storage:', error);
    }
  }

  async removeItem(key: StorageKey): Promise<void> {
    try {
      await this.storage.removeItem(key);
    } catch (error) {
      console.error('Error removing item from storage:', error);
    }
  }

  async multiGet(keys: StorageKey[]): Promise<StorageKeyValuePair[]> {
    try {
      return await this.storage.multiGet(keys);
    } catch (error) {
      console.error('Error getting multiple items from storage:', error);
      return [];
    }
  }

  async multiRemove(keys: StorageKey[]): Promise<void> {
    try {
      await this.storage.multiRemove(keys);
    } catch (error) {
      console.error('Error removing multiple items from storage:', error);
    }
  }
}

export const storage = Storage.getInstance();

interface FileUploadResponse {
  url: string;
}

interface FileToUpload {
  uri: string;
  type: string;
  name: string;
}

export async function uploadFile(file: FileToUpload): Promise<string> {
  try {
    const formData = new FormData();
    formData.append('file', {
      uri: file.uri,
      type: file.type,
      name: file.name,
    } as any);

    const response = await axios.post<FileUploadResponse>(
      `${API_BASE_URL}/upload`,
      formData,
      {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      }
    );

    return response.data.url;
  } catch (error) {
    console.error('File upload error:', error);
    throw new Error('文件上传失败');
  }
} 